package com.wangl.generator.wlmybatisgenerator.listener;

import com.wangl.generator.wlmybatisgenerator.data.DataStore;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;

/**
 * @ClassName AutoCompleter
 * @Description 下拉框事件监听器
 * @Author wangl
 * @Date 2021/11/26 17:34
 */
public class AutoCompleter implements KeyListener {

    private JComboBox<String> owner = null;
    private JTextField editor = null;
    private ComboBoxModel<String> model = null;
    private String type = null;

    public AutoCompleter(JComboBox<String> comboBox, String type){
        this.owner = comboBox;
        editor = (JTextField) comboBox.getEditor().getEditorComponent();
        editor.addKeyListener(this);
        model = comboBox.getModel();
        this.type = type;
    }

    @Override
    public void keyTyped(KeyEvent keyEvent) {
        // Do nothing.
    }

    @Override
    public void keyPressed(KeyEvent keyEvent) {
        // Do nothing.
    }

    @Override
    public void keyReleased(KeyEvent keyEvent) {
        char ch = keyEvent.getKeyChar();
        if (ch == KeyEvent.CHAR_UNDEFINED || (Character.isISOControl(ch) && ch != KeyEvent.VK_BACK_SPACE))
            return;
        int caretPosition = editor.getCaretPosition();
        String str = editor.getText();
        autoComplete(str, caretPosition);
    }

    private void autoComplete(String strf, int caretPosition) {
        if (StringUtils.isBlank(strf)){
            return;
        }
        Object[] opts;
        opts = getMatchingOptions(strf.substring(0, caretPosition));
        if (owner != null) {
            model = new DefaultComboBoxModel(opts);
            owner.setModel(model);
        }
        if (opts.length > 0) {
            editor.setCaretPosition(caretPosition);
            if (owner != null) {
                try {
                    owner.showPopup();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    protected Object[] getMatchingOptions(String str) {
        List<String> total = DataStore.databases;
        if (str.length() == 0){
            return total.toArray(new String[0]);
        }
        return total.stream()
                .map(String::toLowerCase)
                .filter(e -> e.startsWith(str.toLowerCase())).toArray(String[]::new);
    }
}
